package org.SPI;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/** 
* @author James
* @date 2018年6月29日 
*/
public class SimpleServiceLoader<T> {
	private static final String META_INF="META-INF/services/";
	
	private List<T> loadList=new ArrayList<>();
	
	private ClassLoader classLoader=null;
	
	private SimpleServiceLoader() {
		classLoader=Thread.currentThread().getContextClassLoader();
		if(classLoader==null) {
			classLoader=ClassLoader.getSystemClassLoader();
		}
	}
	
	public static <T> SimpleServiceLoader<T> load(Class<T> clazz) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
		SimpleServiceLoader<T> loader=new SimpleServiceLoader<>();
		String className=clazz.getName();
		InputStream is=loader.classLoader.getResourceAsStream(META_INF+className);
//		InputStream is=SimpleServiceLoader.class.getClassLoader().getResourceAsStream(META_INF+className);
		BufferedReader br=new BufferedReader(new InputStreamReader(is));
		String line=null;
		while((line=br.readLine())!=null) {
			loader.loadList.add(loader.loadClass(line));
		}
		return loader;
	}
	
	private T loadClass(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		return (T) Class.forName(className).newInstance();
	}
	
	public Iterator<T> iterator() {
		return loadList.iterator();
	}
}
